<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import * as qiniu from 'qiniu-js'
import { getToken } from '@/api/qiniu.js'
import {Delete, Plus, ZoomIn} from "@element-plus/icons-vue"; // 获取七牛上传凭证的 API


const fileList = ref([])

const handleRemove = (uploadFile, uploadFiles) => {
  fileList.value = uploadFiles
}

const handlePreview = (file) => {
  console.log('预览文件:', file)
}

const handleOnChange = (uploadFile, uploadFiles) => {
  if (uploadFile.status !== 'ready') return
  const rawFile = uploadFile.raw

  // ✅ 判断是否是图片类型
  const isImage = rawFile.type.startsWith('image/')
  if (!isImage) {
    ElMessage.warning('只能上传图片类型文件')
    // 移除这个不是图片的文件
    fileList.value = uploadFiles.filter(file => file.uid !== uploadFile.uid)
    return
  }

  // ✅ 重复文件检测
  const isDuplicate = uploadFiles.slice(0, -1).some(file =>
      file.name === rawFile.name && file.raw?.size === rawFile.size
  )

  if (isDuplicate) {
    ElMessage.warning('该图片已选择，请勿重复上传')
    fileList.value = uploadFiles.slice(0, -1)
  }
}


const dialogVisible = ref(false)
const dialogImageUrl = ref('')
const disabled = ref(false)
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true
}

const uploadToQiniu = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请先选择文件')
    return
  }

  try {
    const qiNiu = (await getToken()).data
    const uploadPromises = fileList.value.map(file => {
      return new Promise((resolve, reject) => {
        const key = `uploads/${file.name}` // 自定义上传路径
        const putExtra = {
          fname: file.name,
          params: {},
          mimeType: ["image/png", "image/jpeg", "image/jpg"]
        }
        const config = {
          useCdnDomain: true,
          region: qiniu.region.z2 // 根据您的存储区域设置
        }

        const observable = qiniu.upload(file.raw, key, qiNiu.token, putExtra, config)

        observable.subscribe({
          next: (res) => {
            console.log('上传中', res.total)
          },
          error: (err) => {
            console.error('上传失败', err)
            ElMessage.error(`文件 ${file.name} 上传失败`)
            reject(err)
          },
          complete: (res) => {
            const fileUrl = `${qiNiu.domain}/${res.key}`
            file.url = fileUrl // 更新文件的 URL
            ElMessage.success(`文件 ${file.name} 上传成功`)
            resolve()
          }
        })
      })
    })

    await Promise.all(uploadPromises)
    ElMessage.success('所有文件上传成功')
  } catch (e) {
    console.error('获取上传凭证失败', e)
    ElMessage.error('获取上传凭证失败')
  }
}
</script>
<template>
  <el-upload
      class="upload-demo"
      :auto-upload="false"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-change="handleOnChange"
      v-model:file-list="fileList"
      list-type="picture-card"
      multiple
  >
    <el-icon><Plus /></el-icon>
    <template #file="{ file }">
      <div>
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in /></el-icon>
          </span>
          <span
              v-if="!disabled"
              class="el-upload-list__item-delete"
              @click="handleRemove"
          >
            <el-icon><Delete /></el-icon>
          </span>
        </span>
      </div>
    </template>
  </el-upload>
  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
  <el-button type="success" @click="uploadToQiniu">上传到七牛云</el-button>
</template>
<!--
<el-upload
    class="upload-demo"
    :auto-upload="false"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :on-change="handleOnChange"
    v-model:file-list="fileList"
    list-type="picture"
    multiple
>
<el-button type="primary">选择文件</el-button>
<template #tip>
  <div class="el-upload__tip">
    jpg/png 文件，大小不超过 500kb
  </div>
</template>
</el-upload>
<el-button type="success" @click="uploadToQiniu">上传到七牛云</el-button>-->
